//
//  GNComposeTextView.swift
//  SinaWeChat
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

@IBDesignable class GNComposeTextView: UITextView {
    
    @IBInspectable var placeholder : String? {
        didSet{
            
            placeholderLabel.text = placeholder
            
        }
    }
    
    //重写text属性,为了在didSet 里面更显示或者隐藏 text
    override var text: String? {
        
        didSet{
            placeholderLabel.hidden = hasText()
        }
    }
    
    override var font: UIFont? {
        didSet{
            
            //指定站位文字的控件的字体的大小
            placeholderLabel.font = font
        }
    }
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
    
    super.init(frame: frame, textContainer: textContainer)
    
    setupUI()
    
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
    setupUI()
   }
    
    private func setupUI(){
        
        //添加控件
        addSubview(placeholderLabel)
        
        //添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        
        //监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged", name: UITextViewTextDidChangeNotification, object: nil)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.x = 5
        placeholderLabel.y = 8
    }
    
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK:-监听方法
    
    @objc private func textChanged() {
        
        //根据当亲输入框有没有文字来调整label的隐藏
        placeholderLabel.hidden = hasText()
        
    }
    
    //MARK:-懒加载
    
    private lazy var placeholderLabel:UILabel = {
        
        let label = UILabel()
        
        label.numberOfLines = 0
        label.text = "哈哈哈,发表我的好心情"
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        
        return label
        
    }()

}
